<template>
  <div class="digBox">
    <el-upload
      :action="API + 'uploadPicture'"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <el-button size="small" type="primary">{{ $t("btn.upload") }}</el-button>
    </el-upload>
    <media :media-data="pictures" is-show-del-icon @delMedia="delImg"></media>
  </div>
</template>
  
  <script>
import { getAllPicture, delPicture } from "@/api/";
import media from "@/components/Media";
let API = process.env.VUE_APP_API;
export default {
  components: { media },
  data() {
    return {
      pictures: [],
      API,
    };
  },
  methods: {
    async delImg(item) {
      let picture = item.path.replace(this.API, "");
      let { data } = await delPicture({ picture });
      let { code, message } = data;
      if (code === 20000) {
        this.$message({
          message,
          type: "success",
        });
        this.loadPicture();
      }
    },
    async handleAvatarSuccess(res, file) {
      this.loadPicture();
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    loadPicture() {
      getAllPicture().then(({ data }) => {
        let result = data.map((item) => {
          item.path = API + item.path;
          return item;
        });
        this.pictures = result;
      });
    },
  },
  mounted() {
    this.loadPicture();
  },
};
</script>
  
  <style lang="scss" scoped>
.digBox {
  width: 100%;
  height: 520px;
  overflow: auto;
  background: white;
}
</style>